package net.yxsoft.service;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import net.yxsoft.enumclass.WhetherEnumCls;
import net.yxsoft.kit.Helper;
import net.yxsoft.model.SLifecycModel;
import net.yxsoft.model.SLifecycModelNode;
import net.yxsoft.model.SLifecycModelNodeAcc;
import net.yxsoft.model.formdesigner.Form;
import net.yxsoft.model.infrastructure.TsMenu;
import net.yxsoft.resource.SqlRes;
import net.yxsoft.service.common.BaseService;
import org.apache.commons.lang.StringUtils;
import rapid.core.Authuser;
import rapid.core.TResult;
import rapid.jfinal.Pagination;
import rapid.jfinal.ParamKeyMap;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenhui
 * 生命周期模型管理
 */
public class LifecycleService extends BaseService {

  public static final LifecycleService INSTANCE = new LifecycleService();
  // 生命周期模型DAO
  private static  final SLifecycModel lifecycModelDao = new SLifecycModel().dao();
  // 生命周期模型节点Dao
  private static final SLifecycModelNode lifecycModelNodeDao = new SLifecycModelNode().dao();
  // 生命周期模型节点附件Dao
  private static final SLifecycModelNodeAcc lifeAccDao = new SLifecycModelNodeAcc().dao();

  /**
  * @MethodName: getLifecycModel
  * @Description: 获取生命周期模型列表
  * @param: params
  * @return * @return java.util.List<net.yxsoft.model.SLifecycModel>
  * @throws
  * @date 2023/8/31 15:52
  * @author wj
  */
  public List<SLifecycModel> getLifecycModel(ParamKeyMap params){
    return lifecycModelDao.find(Db.getSqlPara(SqlRes.LIFECYC + "findLifecyc", params.toKv()));
  }

  /**
   * @MethodName: getLifecycModelNode
   * @Description: 获取生命周期模型节点列表
   * @param: params
    * @param: pg
   * @return * @return rapid.jfinal.Pagination
   * @throws
   * @date 2023/8/31 15:53
   * @author wj
   */
  public Pagination getLifecycModelNode(ParamKeyMap params, Pagination pg){

    SqlPara sqlPara = Db.getSqlPara(SqlRes.LIFECYC + "findLifecycNode", params.toKv());
    Page p = Db.paginate(pg.getPageIndex(), pg.getPageSize(), sqlPara);
    pg.bind(p);
    return pg;
  }


  /**
  * @MethodName: getLifecycAcc
  * @Description: 获取生命周期模型节点附件
  * @param: params
  * @return * @return java.util.List<net.yxsoft.model.SLifecycModelNodeAcc>
  * @throws
  * @date 2023/8/31 15:53
  * @author wj
  */
  public List<SLifecycModelNodeAcc> getLifecycAcc(ParamKeyMap params){
    return lifeAccDao.find(Db.getSqlPara(SqlRes.LIFECYC + "findLifecycNodeAcc", params.toKv()));
  }
  /**
   * 新增、修改生命周期模型
   * @param sLifecycModel
   * @return if(StrKit.notBlank ( pid)) {
   *       TsMenu menu = new TsMenu();
   *       menu.setPid(Integer.parseInt(pid));
   *       TResult re = saveMenu(menu, sLifecycModel.getAttrib01(), sLifecycModel.getAttrib02(), idmodel,loginUser);
   *       if(re.isFail()){
   *         return TResult.fail(re.getMessage());
   *       }
   *     }
   */
  public TResult saveLifecycModel(SLifecycModel sLifecycModel,String pid,Integer idmodel,Authuser loginUser){
    if(StrKit.notNull(loginUser)) {
      String Logs = "";
      if(sLifecycModel.getConflictId() == null) {
        //新增
        List<SLifecycModel> list = lifecycModelDao.find("select * from s_lifecyc_model where attrib_01 = ?", sLifecycModel.getAttrib01());
        if(list.size() > 0) {
          return TResult.fail("该名称已存在，请重新输入！");
        }
        List<SLifecycModel> list2 = lifecycModelDao.find("select * from s_lifecyc_model where attrib_02 = ?", sLifecycModel.getAttrib02());
        if(list2.size() > 0) {
          return TResult.fail("该编号已存在，请重新输入！");
        }
        if(sLifecycModel.save()) {
          Logs = "主键:" + sLifecycModel.getConflictId() + "名称：" + sLifecycModel.getAttrib01();
          log(loginUser.getId(), loginUser.getName(), "生命周期模型", "新增", loginUser.getIp(), Logs);
          if(StrKit.notBlank ( pid)) {
            TsMenu menu = new TsMenu();
            menu.setPid(Integer.parseInt(pid));
            TResult re = saveMenu(menu, sLifecycModel.getAttrib01(), sLifecycModel.getAttrib02(), idmodel,loginUser);
            if(re.isFail()){
              return TResult.fail(re.getMessage());
            }
          }
          return TResult.success("新增成功！");
        } else {
          return TResult.fail("新增失败！");
        }
      } else {
        //修改
        List<SLifecycModel> list = lifecycModelDao.find("select * from s_lifecyc_model where attrib_01 = ? and conflict_id <> ?", sLifecycModel.getAttrib01(), sLifecycModel.getConflictId());
        if(list.size() > 0) {
          return TResult.fail("该名称已存在，请重新输入！");
        }
        List<SLifecycModel> list2 = lifecycModelDao.find("select * from s_lifecyc_model where attrib_02 = ? and conflict_id <> ?", sLifecycModel.getAttrib02(), sLifecycModel.getConflictId());
        if(list2.size() > 0) {
          return TResult.fail("该编号已存在，请重新输入！");
        }
        SLifecycModel sLifecycModel1 = lifecycModelDao.findById(sLifecycModel.getConflictId());
        if(sLifecycModel1 == null) {
          return TResult.fail("修改的信息不存在！");
        } else {
          sLifecycModel1.setAttrib01(sLifecycModel.getAttrib01());
          sLifecycModel1.setAttrib02(sLifecycModel.getAttrib02());
          sLifecycModel1.setAttrib15(sLifecycModel.getAttrib15());
          sLifecycModel1.setAttrib19(sLifecycModel.getAttrib19());

          if(sLifecycModel1.update()) {
            Logs = "主键:" + sLifecycModel.getConflictId() + "名称：" + sLifecycModel.getAttrib01();
            log(loginUser.getId(), loginUser.getName(), "生命周期模型", "修改", loginUser.getIp(), Logs);
            if(StrKit.notBlank ( pid)) {
              TsMenu menu = new TsMenu();
              menu.setPid(Integer.parseInt(pid));
              TResult re = saveMenu(menu, sLifecycModel.getAttrib01(), sLifecycModel.getAttrib02(), idmodel,loginUser);
              if(re.isFail()){
                return TResult.fail(re.getMessage());
              }
            }
            return TResult.success("修改成功！");
          } else {
            return TResult.fail("修改信息失败！");
          }
        }
      }
    }else {
      return TResult.fail("未获得用户信息,请重新登录！");
    }
  }


  /**
  * @MethodName: saveLiftcycModelNode
  * @Description: 新增、编辑生命周期模型节点
  * @param: sLifecycModelNode
   * @param: loginUser
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 15:53
  * @author wj
  */
  public TResult saveLiftcycModelNode(SLifecycModelNode sLifecycModelNode,Authuser loginUser){
    Form _form = new Form();
    String[] arr = {};
    String names = "";
    String Logs;
    List<Form> list_form = new ArrayList<>();
    if(sLifecycModelNode.getAttrib12() != null){
      arr = sLifecycModelNode.getAttrib12().split(",");
    }
    if(arr.length > 0){
      for(String _id : arr){
        _form = new Form().dao().findById(_id);
        list_form.add(_form);
      }
    }
    if(list_form.size() > 0){
      for(Form _f : list_form){
        names += _f.getName()+",";
      }
      names = StringUtils.substringBeforeLast(names,",");
    }
    //Form _form = new Form().dao().findById(sLifecycModelNode.getAttrib12());
    if(sLifecycModelNode.getConflictId() == null){
      // 新增
      sLifecycModelNode.setAttrib13(names);
      if(sLifecycModelNode.save()){
        Logs = "主键:" + sLifecycModelNode.getConflictId() + "名称：" + sLifecycModelNode.getAttrib01();
        log(loginUser.getId(), loginUser.getName(), "生命周期模型节点", "新增", loginUser.getIp(), Logs);
        return TResult.success("新增成功！");
      }else {
        return TResult.fail("新增失败！");
      }
    }else {
      // 修改
      SLifecycModelNode sLifecycModelNode1 = lifecycModelNodeDao.findById(sLifecycModelNode.getConflictId());
      if(sLifecycModelNode1 == null){
        return TResult.fail("修改的信息不存在！");
      }
      sLifecycModelNode1.setAttrib01(sLifecycModelNode.getAttrib01());
      sLifecycModelNode1.setAttrib12(sLifecycModelNode.getAttrib12());
      sLifecycModelNode1.setAttrib11(sLifecycModelNode.getAttrib11());
      sLifecycModelNode1.setAttrib13(names);
      sLifecycModelNode1.setAttrib15(sLifecycModelNode.getAttrib15());
        sLifecycModelNode1.setAttrib20(sLifecycModelNode.getAttrib20());
      if(sLifecycModelNode1.update()){
        Logs = "主键:" + sLifecycModelNode.getConflictId() + "名称：" + sLifecycModelNode.getAttrib01();
        log(loginUser.getId(), loginUser.getName(), "生命周期模型节点", "修改", loginUser.getIp(), Logs);
        return TResult.success("修改成功！");
      }else {
        return TResult.fail("修改失败！");
      }
    }
  }

  /**
  * @MethodName: deleteLifecycNode
  * @Description:  根据主键值删除生命周期模型节点
  * @param: ids
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 15:54
  * @author wj
  */
  public TResult deleteLifecycNode(String[] ids){
    if(ids.length > 0){
      List<String> _sqlList = new ArrayList<>();
      for(int i = 0; i < ids.length;i++){
        _sqlList.add(String.format("delete from s_lifecyc_model_node where conflict_id='%s'", ids[i]));
        _sqlList.add(String.format("delete from s_lifecyc_model_node_acc where row_id='%s'",ids[i]));
      }
      Db.batch(_sqlList,10000);
    }else {
      return TResult.fail("您删除的数据不存在或已经被删除！");
    }
    return success();
  }

  /**
  * @MethodName: deleteLifecyc
  * @Description: 根据主键值删除生命周期模型
  * @param: ids
   * @param: authuser
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 15:54
  * @author wj
  */
  public TResult deleteLifecyc(String[] ids,Authuser authuser){
    if(ids.length > 0){
      List<String> _sqlList = new ArrayList<String>();
      for(int i = 0; i < ids.length; i++) {
        List<SLifecycModelNode> lifecycModelNodes = lifecycModelNodeDao.find("select * from s_lifecyc_model_node where row_id=?",ids[i]);
        if(lifecycModelNodes.size() > 0){
          for(SLifecycModelNode sLifecycModelNode : lifecycModelNodes){
            _sqlList.add(String.format("delete from s_lifecyc_model_node_acc where row_id='%s'", sLifecycModelNode.getConflictId()));
          }
        }
        _sqlList.add(String.format("delete from s_lifecyc_model where conflict_id='%s'", ids[i]));
        _sqlList.add(String.format("delete from s_lifecyc_model_node where row_id='%s'", ids[i]));
      }
      Db.batch(_sqlList, 10000);
      log(authuser.getLoginId(), authuser.getName(), "生命周期模型", "删除", authuser.getId(), "主键Ids：" + StringUtils.join(ids, ","));
    }else {
      return fail("您删除的数据不存在或已经被删除！");
    }
    return success();
  }

  /**
  * @MethodName: saveLifecycAcc
  * @Description: 新增、编辑生命周期节点附件
  * @param: sLifecycModelNodeAcc
   * @param: loginUser
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 15:54
  * @author wj
  */
  public TResult saveLifecycAcc(SLifecycModelNodeAcc sLifecycModelNodeAcc,Authuser loginUser){
    String Logs;
    if(sLifecycModelNodeAcc.getConflictId() == null){
      //新增
      if(sLifecycModelNodeAcc.save()){
        Logs = "主键:" + sLifecycModelNodeAcc.getConflictId() + "名称：" + sLifecycModelNodeAcc.getAttrib01();
        log(loginUser.getId(), loginUser.getName(), "生命周期模型节点", "新增", loginUser.getIp(), Logs);
        return TResult.success("新增成功！");
      }else {
        return TResult.fail("新增失败");
      }
    }else {
      //修改
      SLifecycModelNodeAcc sLifecycModelNodeAcc1 = lifeAccDao.findById(sLifecycModelNodeAcc.getConflictId());
      if(sLifecycModelNodeAcc1 == null){
        return TResult.fail("您编辑的信息不存在！");
      }
      sLifecycModelNodeAcc1.setAttrib01(sLifecycModelNodeAcc.getAttrib01());
      sLifecycModelNodeAcc1.setAttrib15(sLifecycModelNodeAcc.getAttrib15());
      if(sLifecycModelNodeAcc1.update()){
        Logs = "主键:" + sLifecycModelNodeAcc.getConflictId() + "名称：" + sLifecycModelNodeAcc.getAttrib01();
        log(loginUser.getId(), loginUser.getName(), "生命周期模型节点", "修改", loginUser.getIp(), Logs);
        return TResult.success("编辑成功！");
      }else {
        return TResult.fail("编辑失败！");
      }
    }
  }

  /**
  * @MethodName: deleteLifecycAcc
  * @Description: 根据主键值删除生命周期模型节点附件
  * @param: _idArr
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 15:54
  * @author wj
  */
  public TResult deleteLifecycAcc(String[] _idArr){
    if(_idArr.length > 0){
      List<String> _sqlList = new ArrayList<>();
      for(int i = 0; i < _idArr.length; i++) {
        _sqlList.add(String.format("delete from s_lifecyc_model_node_acc where conflict_id='%s'", _idArr[i]));
      }
      Db.batch(_sqlList, 10000);
    }else {
      return fail("您删除的数据不存在或已经被删除！");
    }
    return success();
  }

  /**
  * @MethodName: getForm
  * @Description: 模糊查询关联表单
  * @param: orgname
  * @return * @return java.util.List<net.yxsoft.model.formdesigner.Form>
  * @throws
  * @date 2023/8/31 15:54
  * @author wj
  */
  public List<Form> getForm(String orgname){
    List<Form> list = new ArrayList<Form>();
    StringBuilder _strSql = new StringBuilder();
    _strSql.append(" select id ,name from fn_form  \n" +
                     "where 1=1 and type=0 \n");
    if(rapid.util.StrKit.notBlank(orgname)) {
      _strSql.append(Helper.getVagueQuery(orgname, "name", true));
    }
    list = new Form().dao().find(_strSql.toString());
    return list;
  }

  /**
  * @MethodName: saveMenu
  * @Description: 保存生命周期菜单
  * @param: model
   * @param: exampleName
   * @param: exampleCode
   * @param: ismodel
   * @param: loginUser
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 15:55
  * @author wj
  */
  public TResult saveMenu(TsMenu model, String exampleName, String exampleCode, Integer ismodel,Authuser loginUser) {
    Record isExist = Db.findFirst("select id from ts_menu \n" +
                                    " where menu_code =? ", exampleCode);
    if(null== isExist){
      List<Record> records = Db.find(" select max(a.code) mcode,max(a.sort_id) sortid,b.code pcode from ts_menu a\n" +
                                       "left join ts_menu b on \n" +
                                       "a.pid = b.id where a.pid=?  group by b.code", model.getPid());
      TsMenu _top_menu = TsMenu.dao.findFirst("select * from ts_menu where id=?", model.getPid());

      if(_top_menu == null) {
        return TResult.fail("生命周期表单首级菜单不存在！");
      }

      int _mcode = 1;
      int _sortid = 1;
      String code="";
      if(records.size() > 0) {
        _mcode = Integer.parseInt(records.get(0).getStr("mcode")) + 1;
        _sortid = Integer.parseInt(records.get(0).getStr("sortid")) + 1;
      }else{
          code = _top_menu.getCode() + "01";
          _sortid = 0;
      }
      int sort = _sortid;
      if(StrKit.isBlank(code)) {
          code = Integer.toString(_mcode);
      }
      model.setCode(code);
      model.setSortId(sort);
      model.setVisible(WhetherEnumCls.YES.getValue());
      model.setEnabled(WhetherEnumCls.YES.getValue());
      model.setType("2");
      model.setName(exampleName);
      model.setPath("/sysadmin/life?code="+exampleCode + "&ismodel="+ ismodel );
      model.setMenuType("LIFECYC");
      model.setMenuCode(exampleCode);
      if(model.save() != true) {
        return TResult.fail("保存失败！");
      }
      log(loginUser.getId(), loginUser.getName(), "生命周期/生命周期模型", "创建菜单", loginUser.getIp(), "非普通菜单编号：" + model.getMenuCode());
    }else {
      return TResult.fail("创建菜单失败，非普通菜单编号已存在！");
    }
    return success();
  }

  /**
  * @MethodName: getMenus
  * @Description: 获取生命周期菜单
  * @param:
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws
  * @date 2023/8/31 15:55
  * @author wj
  */
  public List<Record> getMenus() {
    StringBuilder _strSql = new StringBuilder();
    _strSql.append("select * from ts_menu where menu_type='LIFECYC' and type='1' and pid=0 and enabled='1' order by sort_id desc");
    List<Record> _returnData = new ArrayList<Record>();
    String resultSql = _strSql.toString();
    _returnData = Db.find(resultSql);
    return _returnData;
  }

}
